function FBArray = CKMEANARRAY(Dyn, KSpan, Kfb)

%--------------------------------------------------------------------------
% function CKMEANARRAY *Created by PEIWEN CONG* 23.11.10
% generating averaging array within span with varias length Ki
%
% INPUT
% Dyn:      time series of observations
% KSpan:    Span center at kk or single k
% Kfb:      K forward backward vector
%
% OUTPUT
% FBArray:  Mean with 2M * 2K or 2K
%--------------------------------------------------------------------------

FBArray = zeros(length(Kfb), length(KSpan));

for i = 1:length(Kfb)
    for j = 1:length(KSpan)
        if Kfb(i) > 0 % forward
            if KSpan(j) > 1
                FBArray(i,j) = mean(Dyn( max(1, (KSpan(j)-abs(Kfb(i)))):(KSpan(j)-1) ));
            else % boundary set to mean; result in 0 after subtraction
                FBArray(i,j) = Dyn(KSpan(j));
            end
        elseif Kfb(i) < 0 % backward
            if KSpan(j) < length(Dyn)
                FBArray(i,j) = mean(Dyn( (KSpan(j)+1):min((KSpan(j)+abs(Kfb(i))),length(Dyn)) ));
            else % boundary set to mean; result in 0 after subtraction
                FBArray(i,j) = Dyn(KSpan(j));
            end
        end
    end
end